package com.lizhi.note.controller;

import com.lizhi.note.config.provider.CustomUser;
import com.lizhi.note.dto.NotebookLastVisitDTO;
import com.lizhi.note.payload.ResponseUtil;
import com.lizhi.note.service.NotebookLastVisitService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;

@RestController
@RequestMapping("/api/notebook-last-visit")
public class NotebookLastVisitController {

    private final NotebookLastVisitService service;

    public NotebookLastVisitController(NotebookLastVisitService service) {
        this.service = service;
    }

    @PostMapping
    public ResponseEntity<?> save(@RequestBody NotebookLastVisitDTO dto) {
        NotebookLastVisitDTO dtoResult =  service.save(dto);
        return ResponseUtil.success(dtoResult, "保存成功");
    }

    @GetMapping
    public ResponseEntity<?> getByNotebookCurrentUser() {
        CustomUser user = this.getCurrentUserDetail();
        NotebookLastVisitDTO dto = service.findByUserId(user.getUserId());
        return ResponseUtil.success(dto);
    }

    public CustomUser getCurrentUserDetail(){
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        CustomUser user = (CustomUser) authentication.getPrincipal();
        return user;
    }
}
